package com.maizhi.controller;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;

import com.maizhi.httpmodel.SessionInfo;
import com.maizhi.httpmodel.UserI;
import com.maizhi.util.CustomDateEditor;
import com.maizhi.util.ResourceUtil;

/**
 * 基础控制器，其他控制器需extends此控制器获得initBinder自动转换的功能
 * 
 */
@Controller
@RequestMapping("/baseController")
public class BaseController {

	private static final Logger logger = Logger.getLogger(BaseController.class);
	
	protected HttpServletRequest request ; 

	protected HttpServletResponse response ;
	
	protected HttpSession session;

	/**
	 * 将前台传递过来的日期格式的字符串，自动转化为Date类型
	 * 
	 * @param binder
	 * 
	 */
	@InitBinder
	public void initBinder(ServletRequestDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		// dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
		// binder.registerCustomEditor(String.class, new StringTrimmerEditor(false));
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}
	
	public HttpSession getSession() {
		return session;
	}

	public void setSession(HttpSession session) {
		this.session = session;
	}
	
	//获取当前登录用户
	public UserI loginUser() {
		SessionInfo sessionInfo;
		try{
			sessionInfo = (SessionInfo)this.session.getAttribute(ResourceUtil.getSessionInfoName());
			if(sessionInfo==null){
				return null;
			}
		}catch(Exception e){
			return null;
		}
		return sessionInfo.getUser();
	}
}

	
